package com.lzj.myvideo.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.lzj.myvideo.common.Const.statusConstant;
import com.lzj.myvideo.common.MediaUtil;
import com.lzj.myvideo.common.ServerResponse;
import com.lzj.myvideo.service.BgmService;
import com.lzj.myvideo.service.VideoServer;

import com.shortvideo.dao.*;
import com.shortvideo.pojo.*;
import com.shortvideo.vo.videoVo;
import org.apache.commons.io.IOUtils;
import org.omg.PortableServer.SERVANT_RETENTION_POLICY_ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.lzj.myvideo.common.Const.pathConstant.*;


@Service
public class VideoServiceImpl implements VideoServer {

    @Autowired
    private videosVoMapper videosVoMapper;

    @Autowired
    private videosMapper videosMapper;

    @Autowired
    private BgmService bgmService;

    @Autowired
    private userMapper userMapper;

    @Autowired
    private userLikeVoMapper userLikeVoMapper;

    @Autowired
    private user_videoMapper user_videoMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private commentsMapper commentsMapper;

    public static String USER_VIDEO_RECORD = "user_video_record";

    //视频最终全路径
    String finalVideoPath = "";
    //封面最终全路径
    String finalCoverPath = "";

    //视频存储在数据库的路径
    String videoDBPath = "";
    //封面存储在数据库的路径
    String coverDBPath = "";



    MediaUtil mediaUtil = new MediaUtil(FFMPEG_EXE_PATH);

    @Override
    public ServerResponse videoUpload(String userId, MultipartFile file) {


        videoDBPath = VIDEO_PATH + userId;

        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        try {
            if (file != null) {
                String filename = file.getOriginalFilename();               //  VID_20191009_162230.mp4
                finalVideoPath = DISK_PATH  + videoDBPath + "/" +filename;       //  F:/shortVdeoFile/video/用户id/VID_20191009_162230.mp4
                videoDBPath += ("/"+filename);                                   //  video/用户id/VID_20191009_162230.mp4

                File videoFile = new File(finalVideoPath);
                if (videoFile.getParentFile() != null || videoFile.getParentFile().isDirectory() ){
                    videoFile.getParentFile().mkdirs();
                }
                fileOutputStream = new FileOutputStream(videoFile);
                inputStream = file.getInputStream();
                IOUtils.copy(inputStream,fileOutputStream);
            }else{
                return ServerResponse.createByError("文件为空");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream!= null){
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ServerResponse.createBySuccess();
    }

    @Override
    public ServerResponse BgmUpload(String userId, MultipartFile file, String bgmId,String seconds) {
        //视频去掉后缀的全名
        String fileNamePrefix = "";

        String filename = file.getOriginalFilename();
        String[] split = filename.split("\\.");
        //  获取文件前缀名
        //  VID_20191009_162230
        for (int i = 0; i < split.length - 1; i++) {
            fileNamePrefix += split[i];
        }
        bgm bgm = bgmService.queryBgmById(bgmId);
        String bgmFullNamePath = DISK_PATH + bgm.getPath();
        String TmpVideoPath = DISK_PATH + VIDEO_PATH + userId + "/" + fileNamePrefix + "_Temp" + ".mp4";   //  F:/shortVdeoFile/video/用户id/VID_20191009_162230_Temp.mp4


        try {
            mediaUtil.removeAudio(finalVideoPath,TmpVideoPath);
            mediaUtil.merger(TmpVideoPath,bgmFullNamePath,Double.valueOf(seconds),finalVideoPath);
            File file1 = new File(TmpVideoPath);
            file1.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ServerResponse.createBySuccess();
    }

    @Override
    public ServerResponse coverUpload(String userId, MultipartFile file) {
        //视频去掉后缀的全名
        String fileNamePrefix = "";

        String filename = file.getOriginalFilename();
        String[] split = filename.split("\\.");
        //  获取文件前缀名
        //  VID_20191009_162230
        for (int i = 0; i < split.length - 1; i++) {
            fileNamePrefix += split[i];
        }
        finalCoverPath = DISK_PATH + VIDEO_PATH + userId + "/" + fileNamePrefix + "_Cover" + ".jpg";
        coverDBPath = VIDEO_PATH + userId + "/" + fileNamePrefix + "_Cover" + ".jpg";
        try {
            mediaUtil.getCover(finalVideoPath,finalCoverPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ServerResponse.createBySuccess();
    }

    @Override
    public ServerResponse saveVideo(videos video) {
        video.setId(UUID.randomUUID().toString());
        video.setVideo_path(videoDBPath);
        video.setCover_path(coverDBPath);
        video.setStatus(statusConstant.status.ALLOW);
        video.setStars_counts(0);
        video.setComments_counts(0);
        int insert = videosMapper.insert(video);
        if (insert > 0){
            return ServerResponse.createBySuccess(video);
        }else{
            return ServerResponse.createByError("插入信息发生错误");
        }

    }

    @Override
    public ServerResponse queryVideo(Integer curPageNum) {
        PageHelper.startPage(curPageNum,5);
        List<videoVo> list = videosVoMapper.queryVideo();

        PageInfo<videoVo> videoPageInfo = new PageInfo<>(list);
        System.out.println(videoPageInfo);
        return ServerResponse.createBySuccess(videoPageInfo);
    }

    @Override
    public ServerResponse queryVideoByVideoId(String videoId) {
        videoVo videoVo = videosVoMapper.queryVideoByVideoId(videoId);
        if (videoVo == null){
            return ServerResponse.createByError("查询失败");
        }
        return ServerResponse.createBySuccess(videoVo);
    }

    @Override
    public ServerResponse queryVideoByUserId(String userId) {
        videosExample videosExample = new videosExample();
        com.shortvideo.pojo.videosExample.Criteria criteria = videosExample.createCriteria();
        criteria.andUser_idEqualTo(userId);
        List<videos> videos = videosMapper.selectByExample(videosExample);
        if (videos == null){
            return ServerResponse.createByError("查询失败");
        }
        return ServerResponse.createBySuccess(videos);
    }


    @Override
    @Transactional
    public ServerResponse likeVideo(String userId, String videoId) {
        user_video user_video = new user_video();
        user_video.setUser_id(userId);
        user_video.setVideo_id(videoId);

        int result1 = user_videoMapper.insert(user_video);
        if (result1 < 1 ){
            throw new RuntimeException("数据库插入异常");
        }
        int result2 = userLikeVoMapper.increaseUserStars(userId);
        if (result2 < 1 ){
            throw new RuntimeException("数据库插入异常");
        }
        int result3 = userLikeVoMapper.increaseVideoStars(videoId);
        if (result3 < 1 ){
            throw new RuntimeException("数据库插入异常");
        }
        return ServerResponse.createBySuccess();

    }

    @Override
    @Transactional
    public ServerResponse unlikeVideo(String userId, String videoId) {
        user_videoExample user_videoExample = new user_videoExample();
        com.shortvideo.pojo.user_videoExample.Criteria criteria = user_videoExample.createCriteria();
        criteria.andUser_idEqualTo(userId).andVideo_idEqualTo(videoId);

        int result1 = user_videoMapper.deleteByExample(user_videoExample);
        if (result1 < 1 ){
            throw new RuntimeException("数据库插入异常");
        }
        int result2 = userLikeVoMapper.reductionUserStars(userId);
        if (result2 < 1 ){
            throw new RuntimeException("数据库插入异常");
        }
        int result3 = userLikeVoMapper.reductionVideoStars(videoId);
        if (result3 < 1 ){
            throw new RuntimeException("数据库插入异常");
        }
        return ServerResponse.createBySuccess();

    }

    @Override
    @Transactional
    public Boolean islike(String userId, String videoId) {
        user_videoExample user_videoExample = new user_videoExample();
        com.shortvideo.pojo.user_videoExample.Criteria criteria = user_videoExample.createCriteria();
        criteria.andUser_idEqualTo(userId).andVideo_idEqualTo(videoId);
        List<user_video> user_videos = user_videoMapper.selectByExample(user_videoExample);
        if (user_videos.size() == 0){
            return false;
        }else {
            user_video user_video = user_videos.get(0);
            if (user_video!=null){
                return true;
            }else
                return false;
        }

    }

    @Override
    @Transactional
    public ServerResponse queryUserLikeVideos(String userId) {
        user_videoExample user_videoExample = new user_videoExample();
        com.shortvideo.pojo.user_videoExample.Criteria criteria = user_videoExample.createCriteria();
        criteria.andUser_idEqualTo(userId);
        List<user_video> user_videos = user_videoMapper.selectByExample(user_videoExample);

        ArrayList<String> video_ids = Lists.newArrayList();
        for (int i = 0;i<user_videos.size();i++){
            System.out.println(user_videos.get(i).getVideo_id());
            video_ids.add(user_videos.get(i).getVideo_id());
        }
        List<videos> list = videosMapper.queryVideos(video_ids);
        return ServerResponse.createBySuccess(list);
    }

    @Override
    public ServerResponse queryVideosByVideoId(ArrayList<String> list) {
        List<videos> videos = videosMapper.queryVideos(list);
        for (videos vi : videos){
            System.out.println(vi);
        }
        return ServerResponse.createBySuccess(videos);
    }

    @Override
    @Transactional
    public void addVideoRecord(String userId, String videoId) {
        ListOperations<String, String> operations = stringRedisTemplate.opsForList();
        operations.remove(USER_VIDEO_RECORD + ":" + userId,0,videoId);
        operations.leftPush(USER_VIDEO_RECORD+":"+userId,videoId);
    }

    @Override
    public List<String> queryVideoRecord(String userId) {
        return stringRedisTemplate.opsForList().range(USER_VIDEO_RECORD + ":" + userId,0,-1);
    }

    @Override
    public ServerResponse commentVideos(String userId, String videoId,String content) {
        userExample userExample = new userExample();
        com.shortvideo.pojo.userExample.Criteria criteria = userExample.createCriteria();
        criteria.andIdEqualTo(userId);
        User user = userMapper.selectByExample(userExample);
        comments comments = new comments();
        comments.setVideo_id(videoId);
        comments.setUser_id(userId);
        comments.setU_face_image_path(user.getU_face_image_path());
        comments.setUsername(user.getUsername());
        comments.setContent(content);
        comments.setCreate_time(new Date());
        int insert = commentsMapper.insert(comments);
        if (insert >0){
            return ServerResponse.createBySuccess();
        }else
            return ServerResponse.createByError();

    }

    @Override
    public ServerResponse queryVideoComments(String videoId) {
        commentsExample commentsExample = new commentsExample();
        com.shortvideo.pojo.commentsExample.Criteria criteria = commentsExample.createCriteria();
        criteria.andVideo_idEqualTo(videoId);
        List<comments> comments = commentsMapper.selectByExample(commentsExample);
        return ServerResponse.createBySuccess(comments);
    }


}
